const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 获取面试题列表（按分类分组）
router.get('/questions', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM interview_questions ORDER BY id DESC');
    // 按分类分组
    const grouped = {};
    rows.forEach(q => {
      const tags = q.tags ? q.tags.split(',') : [];
      const item = { ...q, tags };
      if (!grouped[q.category]) grouped[q.category] = [];
      grouped[q.category].push(item);
    });
    res.json({ questions: grouped });
  } catch (err) {
    res.status(500).json({ message: '数据库查询失败', error: err.message });
  }
});

// 新增面试题
router.post('/questions', async (req, res) => {
  try {
    const { title, description, code, analysis, tags, category } = req.body;
    const tagStr = Array.isArray(tags) ? tags.join(',') : (tags || '');
    const [result] = await pool.query(
      'INSERT INTO interview_questions (title, description, code, analysis, tags, category, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())',
      [title, description, code, analysis, tagStr, category]
    );
    res.status(201).json({ message: '新增成功', question: { id: result.insertId, title, description, code, analysis, tags, category } });
  } catch (err) {
    res.status(500).json({ message: '新增失败', error: err.message });
  }
});

// 编辑面试题
router.put('/questions/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const { title, description, code, analysis, tags, category } = req.body;
    const tagStr = Array.isArray(tags) ? tags.join(',') : (tags || '');
    const [result] = await pool.query(
      'UPDATE interview_questions SET title=?, description=?, code=?, analysis=?, tags=?, category=?, updated_at=NOW() WHERE id=?',
      [title, description, code, analysis, tagStr, category, id]
    );
    if (result.affectedRows === 0) return res.status(404).json({ message: '题目不存在' });
    res.json({ message: '编辑成功' });
  } catch (err) {
    res.status(500).json({ message: '编辑失败', error: err.message });
  }
});

// 删除面试题
router.delete('/questions/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const [result] = await pool.query('DELETE FROM interview_questions WHERE id=?', [id]);
    if (result.affectedRows === 0) return res.status(404).json({ message: '题目不存在' });
    res.json({ message: '删除成功' });
  } catch (err) {
    res.status(500).json({ message: '删除失败', error: err.message });
  }
});

// 获取单个面试题详情
router.get('/questions/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const [rows] = await pool.query('SELECT * FROM interview_questions WHERE id=?', [id]);
    if (!rows.length) return res.status(404).json({ message: '题目不存在' });
    const q = rows[0];
    q.tags = q.tags ? q.tags.split(',') : [];
    res.json(q);
  } catch (err) {
    res.status(500).json({ message: '查询失败', error: err.message });
  }
});

// 运行代码
router.post('/run-code', (req, res) => {
  const { code } = req.body;
  try {
    // 这里应该实现代码运行逻辑
    res.json({
      output: '代码运行结果...',
      error: null
    });
  } catch (error) {
    res.json({
      output: null,
      error: error.message
    });
  }
});

module.exports = router; 